package com.qf.commons.core.utils;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * author Ken
 * create_time 2022/11/25
 */
public class JwtUtils {

    //密钥由调用方来决定
    private static String secretKey = "e1de4268-5ba8-4854-84e7-6b4ce89e0e09";
    //有效期也由调用方来决定
    private static long ttl = 2 * 60 * 60 * 1000;
//    private static long ttl = 10 * 1000;


    /**
     * 生成jwt令牌
     * @param key
     * @param content
     * @return
     */
    public static String createJwtToken(String key, Object content){
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put(key, content);

        long now = System.currentTimeMillis();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date(now))//生成时间
                .signWith(SignatureAlgorithm.HS256,secretKey)
                .addClaims(contentMap);
        if(ttl > 0){
            //设置令牌的过期时间
            jwtBuilder.setExpiration(new Date(now+ttl));
        }
        return jwtBuilder.compact();
    }

    /**
     * 解析jwt令牌
     * @param jwtToken
     * @return
     */
    public static Object parseJwtToken(String jwtToken, String key){
        try {
            return Jwts.parser().setSigningKey(secretKey)
                    .parseClaimsJws(jwtToken).getBody().get(key);
        } catch (Throwable t) {
            return null;
        }
    }

    public static void main(String[] args) {
//        String jwtToken = JwtUtils.createJwtToken("user", "张三");
//        System.out.println("获得jwtToken：" + jwtToken);

        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4MzcyMTQ0OS1mMTYzLTQ2YmEtYWFjYy0xZTZhNmJlM2FjMmIiLCJpYXQiOjE2NjkzNjQyOTksInVzZXIiOiLlvKDkuIkiLCJleHAiOjE2NjkzNjQzMDR9.qrU1Tmsvnkg4cmV-uCBlE72jHYtv_HQTGk_zvio2MKI";
        String user = (String) JwtUtils.parseJwtToken(token, "user");
        System.out.println("解析令牌后的结果：" + user);
    }
}
